// Simple tester for http_query_props.js using global fetch (no require)
// Usage examples:
//   node test_http_query_props.js
//   node test_http_query_props.js --url http://localhost:16881/dra/getPropsLatestValue --tenant 1867... --propIds 1,2,3 --projectIds 111,222
// Env vars also supported: TEST_URL, TEST_TENANT, TEST_PROPIDS, TEST_PROJECTIDS

function parseArgs() {
    try {
        const args = (typeof process !== 'undefined' && process.argv) ? process.argv.slice(2) : [];
        const map = {};
        for (let i = 0; i < args.length; i++) {
            const a = args[i];
            if (a.startsWith('--')) {
                const key = a.slice(2);
                const val = args[i + 1] && !args[i + 1].startsWith('--') ? args[++i] : 'true';
                map[key] = val;
            }
        }
        return map;
    } catch (_) {
        return {};
    }
}

async function main() {
    if (typeof fetch === 'undefined') {
        console.error('Global fetch is not available. Use Node 18+ or run via browser/PowerShell/curl.');
        if (typeof process !== 'undefined') process.exitCode = 1;
        return;
    }

    const args = parseArgs();

    const env = (typeof process !== 'undefined' && process.env) ? process.env : {};
    const url = args.url || env.TEST_URL || 'http://localhost:16881/dra/getPropsLatestValue';
    const tenantId = args.tenant || env.TEST_TENANT || '1867135005738803200';
    const propIds = args.propIds || env.TEST_PROPIDS || '7272885147085979648,7273216500604223488,7273216500612612096';
    const projectIds = args.projectIds || env.TEST_PROJECTIDS || '';

    const headers = {
        'Content-Type': 'application/json',
        'tenant-id': tenantId
    };
    const body = { propIds };
    if (projectIds) body.projectIds = projectIds;

    console.log('POST', url);
    console.log('Headers:', headers);
    console.log('Body:', body);

    try {
        const res = await fetch(url, {
            method: 'POST',
            headers,
            body: JSON.stringify(body)
        });
        const text = await res.text();
        let parsed;
        try { parsed = JSON.parse(text); } catch { parsed = text; }
        console.log('Status:', res.status);
        console.log('Response:', typeof parsed === 'string' ? parsed : JSON.stringify(parsed, null, 2));
    } catch (err) {
        console.error('Request failed:', err && err.message ? err.message : String(err));
        if (typeof process !== 'undefined') process.exitCode = 1;
    }
}

(async () => { await main(); })();
